package com.ruoyi.framework.web.service;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.service.ISysUserService;

/**
 * CAS登录服务
 * 
 * @author ruoyi
 */
@Component
@ConditionalOnProperty(prefix = "cas", name = "enabled", havingValue = "true")
public class CasLoginService
{
    private static final Logger log = LoggerFactory.getLogger(CasLoginService.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Resource
    private SysLoginService loginService;

    /**
     * 处理CAS登录，获取令牌
     * 
     * @param request HTTP请求
     * @return 令牌
     */
    public String handleCasLogin(HttpServletRequest request)
    {
        AttributePrincipal principal = (AttributePrincipal) request.getUserPrincipal();
        if (principal != null)
        {
            // 获取CAS登录用户名
            String username = principal.getName();
            
            // 获取用户属性
            Map<String, Object> attributes = principal.getAttributes();
            log.info("CAS用户登录: {} 属性: {}", username, attributes);
            
            if (StringUtils.isNotEmpty(username))
            {
                // 查询用户信息
                SysUser user = userService.selectUserByUserName(username);
                if (user != null)
                {
                    // 记录登录日志
                    AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "CAS单点登录成功"));
                    loginService.recordLoginInfo(user.getUserId());
                    
                    // 创建登录用户
                    LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, null);
                    
                    // 生成token
                    return tokenService.createToken(loginUser);
                }
                else
                {
                    log.error("CAS用户[{}]登录失败，用户不存在", username);
                }
            }
        }
        return null;
    }
} 